package com.jsu.controller;

import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

import net.sf.json.JSONObject;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import com.jsu.bean.Found;
import com.jsu.bean.FoundDetail;
import com.jsu.bean.FoundMessage;
import com.jsu.bean.FoundMessageExample;
import com.jsu.bean.LostMessage;
import com.jsu.dao.FoundMapper;
import com.jsu.dao.FoundMessageMapper;
import com.jsu.dao.LostMessageMapper;
import com.jsu.dao.MatchedMapper;
import com.jsu.dao.UsrMapper;

@RestController
public class GetMessage {

	@Autowired
	LostMessage lostMessage;
	@Autowired
	UsrMapper usrMapper;
	@Autowired
	LostMessageMapper lostMessageMapper;
	@Autowired
	MatchedMapper matchedMapper;
	@Autowired
	FoundMessageMapper foundMessageMapper;
	@Autowired
	FoundDetail foundDetail;
	@Autowired
	Found found;
	@Autowired
	FoundMessage foundMessage;
	@Autowired
	FoundMapper foundMapper;
	//原推送消息接口(现使用轮询实现
	@RequestMapping(path = {"/getMessage"})
	@ResponseBody
	public List<FoundDetail> getMessage(HttpServletRequest request){
		List<FoundDetail> foundDetails = new ArrayList<FoundDetail>();
        String username = request.getParameter("username");
		Integer id = usrMapper.selectIdByName(username);
		if(id!=null){
			List<Integer> lostMessageIds = lostMessageMapper.selectIdsByPro(id);
			if(!lostMessageIds.isEmpty()){
				List<Integer> foundMessageIds = matchedMapper.selectFoundByLost(lostMessageIds);
				matchedMapper.updateTypeByLost(lostMessageIds);
				if(!foundMessageIds.isEmpty()){
					List<Integer> untfoundIds = foundMessageMapper.selectFoundIdsByMessageIds(foundMessageIds);
					List<Integer> foundIds = new ArrayList<>();
					for(Integer i:untfoundIds){
						if(!foundIds.contains(i)){
							foundIds.add(i);
						}
					}
					for(Integer foundId:foundIds){
						Found found = foundMapper.selectByPrimaryKey(foundId);
						FoundMessageExample foundMessageExample = new FoundMessageExample();
						com.jsu.bean.FoundMessageExample.Criteria criteria = foundMessageExample.createCriteria();
						criteria.andFoundIdEqualTo(foundId);
						List<FoundMessage> foundMessages = foundMessageMapper.selectByExample(foundMessageExample);
					    FoundDetail foundDetail = new FoundDetail();
						foundDetail.setFound(found);
					    foundDetail.setFoundMessages(foundMessages);
					    foundDetails.add(foundDetail);
					}
				}
			}
		}
		return foundDetails;
	}
}
